import dayjs from "dayjs";
import React, { useCallback, useEffect, useState } from "react";
import { wjlgetstudent, wjlgetpaper } from "../axiosAPI/wjl";
import { Button } from "antd";
import { useNavigate } from "react-router-dom";
import './Wjlhome.scss'; // 引入 SCSS 样式文件

export default function Wjlhome() {
    let [student, setStudent] = useState({});
    let [paper, setPaper] = useState([]);
    const navigator = useNavigate();

    const getStudent = async () => {
        try {
            let {
                data: { code, data },
            } = await wjlgetstudent({ _id: sessionStorage.getItem("sid") });
            if (code === 200) {
                setStudent(data);
                getPaper(data.clazz._id);
            }
        } catch (error) {
            console.error("获取学生信息失败:", error);
        }
    };

    const getPaper = async (clazzid) => {
        try {
            if (clazzid) {
                let {
                    data: { data, code },
                } = await wjlgetpaper({ clazzid });
                if (code === 200) {
                    setPaper(data);
                }
            }
        } catch (error) {
            console.error("获取试卷信息失败:", error);
        }
    };

    const handleExamClick = (paperId, endTime) => {
        let startTime = Date.now();
        sessionStorage.setItem("startTime", startTime);
        sessionStorage.setItem("stopTimestamp", endTime); // 记录考试结束时间
        navigator(`/wjlkaoshi/?paperid=${paperId}&&sid=${sessionStorage.getItem("sid")}`);
    };

    useEffect(() => {
        getStudent();
    }, []);

    const [timers, setTimers] = useState({});

    useEffect(() => {
        const interval = setInterval(() => {
            setTimers((prevTimers) => {
                const newTimers = { ...prevTimers };
                const now = Date.now();
                paper.forEach((item) => {
                    if (item.time[0] <= now && now <= item.time[1]) {
                        const timerId = item._id;
                        if (!newTimers[timerId]) {
                            newTimers[timerId] = Math.floor((now - item.time[0]) / 1000);
                        } else {
                            newTimers[timerId] += 1; // Increment each timer by 1 second
                        }
                    }
                });
                return newTimers;
            });
        }, 1000);

        return () => clearInterval(interval);
    }, [paper]);

    // WebSocket
    useEffect(() => {
        ws(student.clazz?._id);
    }, [paper]);

    const ws = useCallback((id) => {
        const socket = new WebSocket(`ws://localhost:3003?sid=${sessionStorage.getItem("sid")}`);
        socket.onmessage = (event) => {
            if (event.data === "1") {
                getPaper(id);
            }
        };
        socket.onclose = () => {
            console.log("Disconnected from WebSocket server");
        };
    }, []);

    return (
        <div className="wjlhome">
            <div className="boxleft">
                {paper.map((item) => {
                    const now = Date.now();
                    let buttonLabel = "";
                    let isDisabled = false;

                    if (now < item.time[0]) {
                        buttonLabel = "考试未开始";
                        isDisabled = true; // 禁用按钮
                    } else if (now >= item.time[0] && now <= item.time[1]) {
                        const timeElapsed = Math.floor((now - item.time[0]) / 1000); // 计算已过时间（秒）
                        // if (timeElapsed > 300) {
                        //     // 超过5分钟
                        //     buttonLabel = "考试开始超过五分钟，禁止进入考试";
                        //     isDisabled = true; // 禁用按钮
                        // } 
                        // else
                         {
                            buttonLabel = "进入考试";
                        }
                    } else {
                        buttonLabel = "考试已结束";
                        isDisabled = true; // 禁用按钮
                    }

                    // 计算已用时间
                    const elapsedTime = timers[item._id] || 0;
                    const hours = Math.floor(elapsedTime / 3600);
                    const minutes = Math.floor((elapsedTime % 3600) / 60);
                    const seconds = elapsedTime % 60;

                    return (
                        <div className="paper-item" key={item._id}>
                            <p className="papername">{item.name}</p>
                            <div className="homeimg">
                                <img src="https://cdn7.axureshop.com/demo/2001850/images/%E5%BE%85%E8%80%83%E7%95%8C%E9%9D%A2/u2880.png" alt="" />
                            </div>
                            <div className="bottom">
                                <span>考试时间:</span>
                                <span>{dayjs(item.time[0]).format("YYYY-MM-DD HH:mm")}</span>
                                <span>至</span>
                                <span>{dayjs(item.time[1]).format("YYYY-MM-DD HH:mm")}</span>
                                <br />
                                <span className="score">满分：{item.out}分</span>
                                <span className="duration">考试时长：{Math.floor((item.time[1] - item.time[0]) / (1000 * 60))}分钟</span>
                                <p>
                                    <Button type="primary"
                                        onClick={() => {
                                            if (!isDisabled) {
                                                handleExamClick(item._id, item.time[1]); // 传递结束时间
                                            }
                                        }}
                                        disabled={isDisabled}
                                    >
                                        {buttonLabel}
                                    </Button>
                                </p>
                                {/* 显示计时器 */}
                                {now >= item.time[0] && now <= item.time[1] && (
                                    <p className="elapsed-time">
                                        已用时间：{hours}小时 {minutes}分钟 {seconds}秒
                                    </p>
                                )}
                                {/* 新增查看成绩按钮 */}
                                {now > item.time[1] && (
                                    <p>
                                        <Button type="dashed" onClick={() => navigator(`/look?paperid=${item._id}`)}>查看成绩</Button>
                                    </p>
                                )}
                            </div>
                        </div>
                    );
                })}
            </div>

            <div className="boxright">
                <img src={student.img} alt="" className="student-img" />
                <p>
                    <span>姓名:</span>
                    <span>{student.name}</span>
                </p>
                <p>
                    <span>班级:</span>
                    <span>{student.clazz?.name}</span>
                </p>
                <p>
                    <span>学号:</span>
                    <span>{student.tid}</span>
                </p>
            </div>
        </div>
    );
}
